//
//  USNoticeViewController.m
//  us
//
//  Created by lhx on 2025/7/20.
//

#import "USNoticeViewController.h"
#import "USNoticeModel.h"
#import "USNoticeCell.h"
#import <MJRefresh/MJRefresh.h>

#import "USAskDetailViewController.h"
#import "USTodayTarotController.h"
#import "USTarotCardDetailController.h"
#import "USMemorialDayDetailVC.h"
#import "USMomentsDetailController.h"
#import "USAddOurListSubListController.h"
#import "USAlbumPhotoListController.h"
#import "USLoveCompassViewController.h"
#import "USLoveCompassGuideController.h"
#import "USTarotCard.h"
#import "USRealtimeLocationManager.h"
@interface USNoticeViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSMutableArray <USNoticeModel *>*list;
 
@property (nonatomic, assign) BOOL hasMore;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger pageSize;

@end

@implementation USNoticeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"消息通知";
    
    
    [self setupView];
    [self setupRefresh];
    
    [self.us_tableView.mj_header beginRefreshing];
}

- (void)setupView{
    
    self.us_tableView.delegate = self;
    self.us_tableView.dataSource = self;
    self.us_tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    self.us_tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.us_tableView.backgroundColor = UIColor.clearColor;
    
    [self.us_tableView registerNib:[UINib nibWithNibName:@"USNoticeCell" bundle:nil] forCellReuseIdentifier:@"USNoticeCellID"];
    
    
}
- (void)setupRefresh {
    
    self.currentPage = 1;
    self.pageSize = 15;
    
    @weakify(self)
    self.us_tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self)
        self.currentPage = 1;
        [self getNoticeList];
    }];
    
    self.us_tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        @strongify(self)
        if (self.hasMore) {
            self.currentPage += 1;
            [self getNoticeList];
        } else {
            [self.us_tableView.mj_footer endRefreshingWithNoMoreData];
        }
    }];
}
- (NSMutableArray <USNoticeModel *>*)list {
    if (_list == nil) {
        _list = [NSMutableArray array];
    }
    return _list;
}
- (void)getNoticeList{
    NSDictionary *params = @{ @"current": @(self.currentPage),
                              @"size": @(self.pageSize),
                              @"readType":@(0)
    };
    
    [[EMNetWork shareManager] em_post:NoticeList
                               params:params
                                  hud:nil
                            showError:YES
                              success:^(EMApiModel *api) {
        
        if (!api.success) {
            [self loadingFailed];
            return;
        }
        
        if (self.currentPage == 1) {
            [self.list removeAllObjects];
        }
        
        NSArray *records = [USNoticeModel mj_objectArrayWithKeyValuesArray:api.data[@"noticeList"][@"records"]];
        
        [self.list addObjectsFromArray:records];
        
        
        // 是否还有更多
        self.hasMore = records.count == self.pageSize;
        
        // 结束刷新状态
        [self.us_tableView.mj_header endRefreshing];
        [self.us_tableView.mj_footer endRefreshing];
        
        if (!self.hasMore) {
            [self.us_tableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.us_tableView.mj_footer resetNoMoreData];
        }
        
        if (self.list.count == 0) {
            self.dataState = EmptyDataStateNoData;
        }
        self.us_tableView.mj_footer.hidden = self.list.count == 0;
        
        [self.us_tableView reloadData];
        [self.us_tableView reloadEmptyDataSet];
        
    } fail:^{
        
        
    }];
    
    
}
#pragma mark - net
- (void)readNotiWithModel:(USNoticeModel *)model {
    
    //置为已读
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:@(model.noticeId) forKey:@"noticeId"];
    [param setValue:@(1) forKey:@"isRead"];

    [[EMNetWork shareManager] em_post:NoticeRead
                               params:param
                                  hud:nil
                            showError:NO
                              success:^(EMApiModel *api) {
 
        if (api.success) {
            NSIndexPath *currentIndexPath = [self.list indexOfObject:model] != NSNotFound ? [NSIndexPath indexPathForRow:[self.list indexOfObject:model] inSection:0] : nil;
            if (currentIndexPath) {
                [self.list removeObjectAtIndex:currentIndexPath.row];
                [self.us_tableView deleteRowsAtIndexPaths:@[currentIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            }
        }
    } fail:^{
        
        
    }];
    

}

//获取今日塔罗牌状态
- (void)getTodayTarot{
    [self startLoading];
    [[EMNetWork shareManager] em_post:TarotToday
                               params:nil
                                  hud:nil
                            showError:NO
                              success:^(EMApiModel *api) {
        [self loadingSuccess];

        if (!api.success) {
            return;
        }
        USTarotModel *tarotModel = [USTarotModel mj_objectWithKeyValues:api.data[@"totalTarot"]];

        if (tarotModel.myStatus == 1 && tarotModel.tarotDetailList.count > 0) {
            USTarotCardDetailController *vc = [[USTarotCardDetailController alloc]init];
            if (tarotModel) {
                vc.tarotModel = tarotModel;
                
                for (USTarotDetailModel *detailModel in tarotModel.tarotDetailList) {
                    USTarotCard *card = [USTarotCard new];
                    
                    card = [[USTarotCard alloc] init];
                    card.name = detailModel.tarotTitle;
                    card.orientation = detailModel.orientation;
                    card.imageName = detailModel.tarotTitle;
                    card.answer = detailModel.tarotContent;
                    card.date = [NSDate dateWithTimeIntervalSince1970:detailModel.gmtCreate];
                    if ([detailModel.userId isEqualToString:USUser.user.userId]) {
                        vc.activeCard = card;
                    }else {
                        vc.relActiveCard = card;
                    }
                }
               
            }
            [self.navigationController pushViewController:vc animated:YES];
            
        }else {
            USTodayTarotController *vc = [USTodayTarotController new];
            vc.tarotModel = tarotModel;
            [self.navigationController pushViewController:vc animated:YES];
            
        }
    } fail:^{
        
        [self loadingFailed];

    }];
}
#pragma mark - UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.list.count;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 78;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    USNoticeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"USNoticeCellID"];
    
    USNoticeModel *model = self.list[indexPath.row];
    
    cell.titleLab.text = [NSString stringWithFormat:@"%@%@",USUser.user.relUser.nickname,model.content];
    cell.timeLab.text = model.gmtCreate;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    USNoticeModel *model = self.list[indexPath.row];
    [USFeedbackTool impactSoft];

    [self readNotiWithModel:model];
    if (model.type == USNoticeType_Talk) {
        //1、问答
        USAskDetailViewController *vc = [USAskDetailViewController new];
        vc.dailyTalkId = model.pkId;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (model.type == USNoticeType_Tarot) {
        //2、塔罗牌
        [self getTodayTarot];
    }else if (model.type == USNoticeType_List) {
        //3、清单
        USAddOurListSubListController *vc = [USAddOurListSubListController new];
        vc.sweetChallengeId = model.pkId;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (model.type == USNoticeType_Moment) {
        //4、日记
        USMomentsDetailController *vc = [USMomentsDetailController new];
        vc.moodDiaryId = model.pkId;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (model.type == USNoticeType_MemorialDay) {
        //5、纪念日
        USMemorialDayDetailVC *vc = [USMemorialDayDetailVC new];
        vc.anniversaryId = model.pkId;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (model.type == USNoticeType_Photo) {
        //6、相册
        USAlbumPhotoListController *vc = [USAlbumPhotoListController new];
        vc.albumId = model.pkId;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (model.type == USNoticeType_Location) {
        //7、位置
        [self compassAction:nil];
    }
     
}

- (void)compassAction:(id)sender{
 
    if ([[NSUserDefaults standardUserDefaults]boolForKey:USKeyHaveOpenLoveCompass] == YES) {
        
        USLoveCompassViewController *vc = [USLoveCompassViewController new];
        [self.navigationController pushViewController:vc animated:YES];
        return;
        
    }
    
    USLoveCompassGuideController *vc = [USLoveCompassGuideController new];
    @weakify(self)
    vc.didStartBlock = ^{
        @strongify(self)
        [self.navigationController popViewControllerAnimated:YES];
        [[NSUserDefaults standardUserDefaults]setBool:YES forKey:USKeyHaveOpenLoveCompass];
        [self updateLocationIfNeed];
        [self compassAction:nil];
    };
    [self.navigationController pushViewController:vc animated:YES];
    
}


///当用户开启指南针功能，并且有匹配用户开启
- (void)updateLocationIfNeed{
    
    if (![[NSUserDefaults standardUserDefaults]boolForKey:USKeyHaveOpenLoveCompass]) {
        return;
    }
    
    if (USUser.user.relType != 1) {
        return;
    }
    
    //十分钟传一次
    [[USRealtimeLocationManager shared]startDispatchingWithInterval:60 * 10];
    
}


#pragma mark - DZNEmptyDataSetSource,DZNEmptyDataSetDelegate


- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView{
    
    if (self.dataState == EmptyDataStateLoading) {
        UIView *contentView = [UIView new];
        contentView.frame = CGRectMake(0, 0, self.view.jk_width, 200);
        
        NSString *gifPath = [[NSBundle mainBundle] pathForResource:@"load_page" ofType:@"gif"];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:nil];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.frame = CGRectMake(0, 0, 200, 200);
        [imageView sd_setImageWithURL:[NSURL fileURLWithPath:gifPath]];
        
        [contentView addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.mas_equalTo(200);
            make.center.mas_equalTo(contentView);
        }];
        
        return contentView;
    }
    
    USEmptyView *emptyView = [[USEmptyView alloc] initWithFrame:CGRectMake(0, 0, self.view.jk_width, 0)];
    emptyView.image = [UIImage imageNamed:@"today_Empty"];
    emptyView.title = @"暂时没有消息哦～";
    emptyView.btn.hidden = YES;
    return emptyView;
    
}

- (BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView {
    
    
    return YES; // 允许点击
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    
    
    return YES; // 避免 scrollView 吃掉 touch 事件
}


@end
